<template>
  <div class="size-full">
    <div class="flex h-full gap-5">
      <!-- 左侧面板：用户信息 -->
      <div class="w-[500px] min-w-0 flex-none max-lg:w-full max-lg:flex-1">
        <div class="p-8">
          <div class="pb-5 text-center">
            <div class="mb-4">
              <el-avatar :size="100" :src="userInfo?.avatar || ''">
                {{ userInfo?.username?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
            </div>
            <h2 class="mb-2 text-xl font-medium text-gray-800">{{ userInfo?.username || '' }}</h2>
            <div class="text-sm text-gray-600">{{ userInfo?.roles?.join(', ') || '' }}</div>
          </div>

          <el-divider />

          <!-- 个人资料 -->
          <div class="mb-5 last:mb-0">
            <h3 class="mt-0 mb-5 text-base font-semibold text-gray-800">个人资料</h3>
            <el-form ref="profileFormRef" :model="profileForm" label-width="80px" class="mt-0">
              <el-form-item label="用户名">
                <el-input v-model="profileForm.username" disabled />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="profileForm.phone" placeholder="请输入电话" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="profileForm.remark"
                  type="textarea"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleUpdate">保存</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-divider />

          <!-- 修改密码 -->
          <div class="mb-5 last:mb-0">
            <h3 class="mt-0 mb-5 text-base font-semibold text-gray-800">修改密码</h3>
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="80px"
              class="mt-0"
            >
              <el-form-item label="当前密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  placeholder="请输入当前密码"
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请确认新密码"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 右侧面板：操作日志 -->
      <div class="flex grow flex-col">
        <h3 class="mt-0 mb-5 text-base font-semibold">操作日志</h3>

        <!-- 搜索区域 -->
        <div class="">
          <el-form :inline="true" :model="logSearchForm">
            <el-form-item label="标题">
              <el-input
                v-model="logSearchForm.title"
                placeholder="请输入标题"
                clearable
                class="w-[200px]"
              />
            </el-form-item>
            <el-form-item label="URL">
              <el-input
                v-model="logSearchForm.url"
                placeholder="请输入URL"
                clearable
                class="w-[200px]"
              />
            </el-form-item>
            <el-form-item label="IP">
              <el-input
                v-model="logSearchForm.ip"
                placeholder="请输入IP"
                clearable
                class="w-[200px]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearchLogs">搜索</el-button>
              <el-button @click="handleResetLogSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table v-loading="logLoading" :data="operationLogs" border stripe class="grow">
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="url" label="链接" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="flex items-center">
                <el-input :model-value="row.url" readonly class="mr-2 w-[250px]" />
                <el-button type="primary" link :icon="Link" @click="handleOpenUrl(row.url)">
                  打开
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ip" label="IP" width="150" align="center" />
          <el-table-column prop="createdAt" label="操作时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="mt-5 flex justify-end">
          <el-pagination
            v-model:current-page="logPagination.page"
            v-model:page-size="logPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="logTotal"
            @size-change="handleLogSizeChange"
            @current-change="handleLogCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { changePassword, getUserOperationLogs, updateUserProfile } from '@/api/system/user'
import { useUserStore } from '@/stores/user'
import { to } from '@/utils/promise'
import { Link } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref } from 'vue'

const userStore = useUserStore()
const profileFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 个人资料表单数据
const profileForm = ref({
  username: '',
  email: '',
  phone: '',
  remark: ''
})

// 密码修改表单数据
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码修改表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '当前密码长度至少为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '新密码长度至少为6位', trigger: 'blur' },
    { max: 20, message: '新密码长度最多为20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化表单数据
const initForm = () => {
  if (userInfo.value) {
    profileForm.value = {
      username: userInfo.value.username || '',
      email: userInfo.value.email || '',
      phone: userInfo.value.phone || '',
      remark: userInfo.value.remark || ''
    }
  }
}

// 更新个人资料
const handleUpdate = async () => {
  const [error] = await to(updateUserProfile(profileForm.value))
  if (error) {
    ElMessage.error(error || '更新失败')
    return
  }
  ElMessage.success('更新成功')
  // 更新用户信息
  userStore.setUserInfo({
    ...userInfo.value,
    ...profileForm.value
  })
}

// 修改密码
const handleChangePassword = async () => {
  const [error] = await to<boolean, string>(passwordFormRef.value!.validate())
  if (error) {
    ElMessage.error(error || '表单验证失败')
    return
  }
  const [error2] = await to(changePassword(passwordForm.value))
  if (error2) {
    ElMessage.error(error2 || '密码修改失败')
    return
  }
  ElMessage.success('密码修改成功')
  // 重置密码表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  // 提示用户重新登录
  ElMessage({
    type: 'info',
    message: '请使用新密码重新登录',
    duration: 3000
  })
}

// 操作日志相关
const logLoading = ref(false)
const operationLogs = ref<UserOperationLog[]>([])
const logTotal = ref(0)
const logSearchForm = ref<Pick<UserOperationLogQueryParams, 'title' | 'url' | 'ip'>>({
  title: '',
  url: '',
  ip: ''
})
const logPagination = ref<Pick<UserOperationLogQueryParams, 'page' | 'pageSize'>>({
  page: 1,
  pageSize: 10
})

// 加载操作日志
const loadOperationLogs = async () => {
  logLoading.value = true
  try {
    const params: UserOperationLogQueryParams = {
      page: logPagination.value.page,
      pageSize: logPagination.value.pageSize,
      ...(logSearchForm.value.title && { title: logSearchForm.value.title }),
      ...(logSearchForm.value.url && { url: logSearchForm.value.url }),
      ...(logSearchForm.value.ip && { ip: logSearchForm.value.ip })
    }
    const [error, data] = await to(getUserOperationLogs(params))
    if (error) {
      ElMessage.error(error || '获取操作日志失败')
      return
    }
    if (data) {
      operationLogs.value = data.list || []
      logTotal.value = data.total || 0
    }
  } finally {
    logLoading.value = false
  }
}

// 搜索操作日志
const handleSearchLogs = () => {
  logPagination.value.page = 1
  loadOperationLogs()
}

// 重置搜索
const handleResetLogSearch = () => {
  logSearchForm.value = {
    title: '',
    url: '',
    ip: ''
  }
  logPagination.value.page = 1
  loadOperationLogs()
}

// 分页大小改变
const handleLogSizeChange = () => {
  loadOperationLogs()
}

// 当前页改变
const handleLogCurrentChange = () => {
  loadOperationLogs()
}

// 打开URL
const handleOpenUrl = (url: string) => {
  if (url) {
    // 如果是相对路径，添加基础URL
    if (url.startsWith('/')) {
      window.open(`${window.location.origin}${url}`, '_blank')
    } else {
      window.open(url, '_blank')
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 组件挂载时初始化
onMounted(() => {
  initForm()
  loadOperationLogs()
})
</script>

<style scoped>
/* 使用 Tailwind CSS，保留必要的 Element Plus 深度样式 */

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 搜索表单中的表单项间距 */
:deep(.el-form--inline .el-form-item) {
  margin-bottom: 15px;
}
</style>
